import {
    _decorator,
    Component,
    Node,
    Texture2D,
    SpriteFrame,
    Sprite,
    ImageAsset,
    view,
    ResolutionPolicy,
    UITransform,
    Label,
    Canvas,
    Material
} from 'cc';

const {ccclass, property} = _decorator;
import 'minigame-api-typings';
import 'three.js'

@ccclass('ARController')
export class ARController extends Component {
    private screenWidth: number;
    private screenHeight: number;
    private camera = null;

    @property(Node)
    openAR: Node;

    @property(SpriteFrame)
    arSpriteFrame: SpriteFrame = null;

    @property(Node)
    spriteNode: Node = null;

    @property(Node)
    ballCamera: Node = null;

    @property(Node)
    spriteBall: Node = null;

    @property(Canvas)
    arCanvas: Canvas;

    private sprite;

    private texture: Texture2D;

    private spriteFrame: SpriteFrame;

    private bufferData;


    private arIsOpen: boolean = false;


    start() {

        const frameSize = view.getFrameSize();

        const info = wx.getWindowInfo();
        this.screenWidth = frameSize.width
        this.screenHeight = frameSize.height

        console.warn('999999999999999999999999999999999999999999999999999999999999')
        console.warn('screenWidth', this.screenWidth)
        console.warn('screenHeight', this.screenHeight)
        console.warn('999999999999999999999999999999999999999999999999999999999999')

        view.setResizeCallback(() => this.adapterScreen());
        this.adapterScreen();

        const uiTransform = this.spriteNode.getComponent(UITransform);
        uiTransform.setContentSize(this.screenWidth * 2, this.screenHeight * 2)
        //
        // this.spriteNode.active = false;
        // this.ballCamera.active = false;
        // this.spriteBall.active = false;


    }

    private adapterScreen() {
        // 获取浏览器视口尺寸
        const screenSize = view.getVisibleSize();

        // 动态设置设计分辨率（保持宽高比）
        view.setDesignResolutionSize(screenSize.width, screenSize.height,
            ResolutionPolicy.SHOW_ALL// 或 FIXED_WIDTH/FIXED_HEIGHT
        );
    }

    onOpenAr() {
        function requestLocationPermission() {


            console.log('------------wx.authorize-------------start');
            wx.authorize({
                scope: 'scope.userLocation',
                success() {
                    console.log('------------wx.authorize-------------success');
                    getLocation(); // 授权成功
                },
                fail() {
                    console.log('------------wx.authorize-------------fail');
                    // 用户拒绝，提示手动开启
                    wx.showModal({
                        title: '定位权限被拒绝',
                        content: '需要您授权位置信息以提供附近服务',
                        success(res) {
                            if (res.confirm) {
                                // 跳转到设置页
                                wx.openSetting({
                                    success: (settingRes) => {
                                        // 检查设置页面返回的授权状态
                                        if (settingRes.authSetting['scope.userLocation']) {
                                            wx.showToast({
                                                title: '权限已开启',
                                                icon: 'none'
                                            });
                                            // resolve(true);
                                        } else {
                                            // 用户没有在设置页面开启权限
                                            wx.showToast({
                                                title: '权限未开启',
                                                icon: 'none'
                                            });
                                        }
                                    },
                                    fail: () => {
                                    }
                                });
                            }
                        }
                    });
                }
            });
        }
        function getLocation() {
            wx.getLocation({
                type: 'gcj02', // 必须使用火星坐标系
                isHighAccuracy: true, // 高精度模式
                highAccuracyExpireTime: 5000, // 5秒超时
                success(res) {
                    console.log('经度:', res.longitude, '纬度:', res.latitude);
                },
                fail(err) {
                    console.error('定位失败:', err.errMsg);
                }
            });
        }
        console.log('-----------------------wx.getSetting--------------------start');
        wx.getSetting({
            success(res) {
                console.log('-----------------------wx.getSetting--------------------success:',res);
                const locationAuth = res.authSetting['scope.userLocation'];
                if (locationAuth === undefined) {
                    // 未询问过权限，发起授权请求
                    requestLocationPermission();
                } else if (locationAuth === false) {
                    // 用户已拒绝，引导手动开启
                    // showPermissionGuide();
                    console.log('用户已拒绝，引导手动开启')
                } else {
                    // 已授权，直接获取位置
                    getLocation();
                }
            }
        });

        return;

        const label = this.openAR.getChildByName('btnArLabel').getComponent(Label);
        if (this.arIsOpen) {
            this.stopAR();
            label.string = 'openAR';
            this.arIsOpen = false;
            return;
        }
        this.arIsOpen = true;
        label.string = 'closeAR';

        this.initVK()
        // this.camera = wx.createCamera({
        //     width: _this.screenWidth,
        //     height: _this.screenHeight,
        //     devicePosition: 'back',
        //     x: _this.screenWidth + 100,
        //     flash: 'off',
        //     size: 'small',
        //     success: res => {
        //         console.log('打开相机成功', res);
        //         _this.camera.listenFrameChange();
        //         this.sprite = this.spriteNode.getComponent(Sprite);
        //         _this.spriteNode.active = true;
        //         _this.ballCamera.active = true;
        //         _this.spriteBall.active = true;
        //
        //         this.initVK({
        //             cameraPosition: 1
        //         })
        //
        //     },
        //     fail: res => {
        //         console.log('打开相机失败', res);
        //         _this.camera.destroy();
        //     }
        // });


        // this.camera.onAuthCancel(res => {
        //     console.log('用户未授权使用摄像头', res);
        // });
        //
        // this.camera.onCameraFrame(frame => {
        //     // 不直接使用 frame 数据绘制，由 vk.getVKFrame 渲染
        //     // console.log("***************************************",frame)
        //     // _this.sprite.spriteFrame = this.arSpriteFrame;
        //
        //     const width = frame.width;
        //     const height = frame.height;
        //
        //     // 包装成 Uint8ClampedArray，确保是 RGBA 格式
        //     const data = new Uint8ClampedArray(frame.data);
        //
        //     if (!_this.texture) {
        //         // 第一次创建 Texture 和 SpriteFrame
        //         const texture = new Texture2D();
        //         texture.reset({
        //             width,
        //             height,
        //             format: Texture2D.PixelFormat.RGBA8888,
        //         });
        //         texture.uploadData(data);
        //
        //         const spriteFrame = new SpriteFrame();
        //         spriteFrame.texture = texture;
        //
        //         _this.texture = texture;
        //         _this.spriteFrame = spriteFrame;
        //         _this.sprite.spriteFrame = spriteFrame;
        //     } else {
        //         // 后续只上传数据
        //         _this.texture.uploadData(data);
        //     }
        //
        //
        // });
        //
        // this.camera.onStop(res => {
        //     console.log('摄像头已停止:', res);
        // });
    }

    initVK() {
        // 离屏画布无需重复创建
        let offScreenCanvas = wx.createCanvas()
        offScreenCanvas.width = this.screenWidth
        offScreenCanvas.height = this.screenHeight
        let offScreenContext = offScreenCanvas.getContext("webgl")
        this.sprite = this.spriteNode.getComponent(Sprite);


        // config.gl = this.gl
        const session = wx.createVKSession({
            track: {
                plane: {mode: 1},
                marker: true,
                OSD: true
            },
            version: 'v1',
            gl: offScreenContext
        });

        session.start(err => {
            if (err) return console.error('VK error: ', err)

            // 逐帧渲染
            const onFrame = timestamp => {
                const frame = session.getVKFrame(this.screenWidth, this.screenHeight)

                // console.log('====vkFrame:', frame)
                if (frame) {
                    console.log('====vkFrame:', frame);

                    // 确保宽高为 16 的倍数
                    const width = 320;
                    const height = 240;
                    const expectedByteLength = width * height * 4;

                    const buffer = frame.getCameraBuffer(width, height);
                    console.warn("buffer length", buffer?.byteLength);

                    // 校验 buffer 是否有效、长度是否一致
                    if (!buffer || buffer.byteLength !== expectedByteLength) {
                        console.warn("⚠️ 无效 buffer 或尺寸异常，跳过该帧：", buffer?.byteLength);
                        session.requestAnimationFrame(onFrame);
                        return;
                    }

                    // 初始化或重置缓冲区
                    if (!this.bufferData || this.bufferData.length !== expectedByteLength) {
                        this.bufferData = new Uint8ClampedArray(expectedByteLength);
                    }

                    // 安全复制 buffer 内容
                    this.bufferData.set(new Uint8ClampedArray(buffer));

                    // 初始化纹理与 spriteFrame
                    if (!this.texture) {
                        console.log("🆕 初始化纹理和 spriteFrame");

                        const texture = new Texture2D();
                        texture.reset({
                            width,
                            height,
                            format: Texture2D.PixelFormat.RGBA8888,
                        });
                        texture.uploadData(this.bufferData);

                        const spriteFrame = new SpriteFrame();
                        spriteFrame.texture = texture;

                        this.texture = texture;
                        this.spriteFrame = spriteFrame;
                        this.sprite.spriteFrame = spriteFrame;
                    } else {
                        // 更新纹理数据
                        this.texture.uploadData(this.bufferData);
                    }
                }

                session.requestAnimationFrame(onFrame)
            }
            session.requestAnimationFrame(onFrame)
        })
        session.on('addAnchors', anchors => {
            console.log('addAnchors:', anchors);
        })
        session.on('updateAnchors', anchors => {
            console.log('updateAnchors:', anchors);
        })
        session.on('removeAnchors', anchors => {
            console.log('removeAnchors:', anchors);
        })


    }


    stopAR() {
        if (this.camera) {
            this.camera.destroy();
            this.camera = null;
        }
        this.spriteNode.active = false;
        this.ballCamera.active = false;
        this.spriteBall.active = false;

    }

}


